package com.wangzhen.codebase.transfermoney.lock2;

/**
 * 此版本和lock1的实现思路不同的地方在于，lock1是通过同时申请两把锁来避免死锁，
 * 该版本的一个思路是在锁资源上加上一个序号，把要加锁的两个资源进行排序，通过这种方式来避免资源
 */
public class Account {

    private Integer id;
    private Integer balance;

    private Account(Integer id, Integer balance) {
        this.id = id;
        this.balance = balance;
    }

    public void transfer(Account target, Integer account) {
        Account left = this;
        Account right = target;
        if (left.id > target.id) {
            left = target;
            right = this;
        }
        synchronized (left) {
            synchronized (right) {
                if (this.balance >= account) {
                    this.balance -= account;
                    target.balance += account;
                } else {
                    System.out.println("余额不足");
                }
            }
        }
    }
}
